import { getCartList, changeCart, deleteCart } from '@/api/product'
import { Toast } from 'vant'
export default {
  namespaced: true,
  state () {
    return {
      cartTotal: '',
      list: []
    }
  },
  mutations: {
    getCartList (state, msg) {
      state.cartTotal = msg.cartTotal
      state.list = msg.list
    },
    changeStatus (state, id) {
      const obj = state.list.find(item => item.goods_id === id)
      // console.log(obj.isChecked)
      obj.isChecked = !obj.isChecked
      // console.log(obj.isChecked)
    },
    toggleAllCheck (state, status) {
      state.list.forEach(e => {
        e.isChecked = status
      })
    },
    changeOneCount (state, { goodsId, goodsNum, goodsSkuId }) {
      const obj = state.list.find(e => e.goods_id === goodsId)
      obj.goods_num = goodsNum
    },
    showList (state, id) {
      state.list = state.list.filter(item => item.goods_id !== id)
    }
  },
  getters: {
    getTotalPrice (state) {
      const newlist = state.list.filter(item => item.isChecked)
      return newlist.reduce((sum, item) => sum + item.goods.goods_price_min * item.goods_num, 0).toFixed(2)
    },
    getTotalCount (state) {
      const newlist = state.list.filter(item => item.isChecked)
      return newlist.reduce((sum, item) => item.goods_num + sum, 0)
    },
    CheckAll (state) {
      return state.list.every(e => e.isChecked)
    },
    getsumCount (state) {
      return state.list.reduce((sum, item) => sum + item.goods_num, 0)
    },
    getChecked (state) {
      const newlist = state.list.filter(item => item.isChecked)
      return newlist
    },
    getCheckedIds (state) {
      const newlist = state.list.filter(item => item.isChecked)
      const ids = newlist.map(item => item.id)
      return ids
    }
  },
  actions: {
    async getCartList (context) {
      const res = await getCartList()
      res.data.list.forEach(element => {
        element.isChecked = true
      })
      context.commit('getCartList', res.data)
    },
    async changeCart (context, { goodsId, goodsNum, goodsSkuId }) {
      await changeCart(goodsId, goodsNum, goodsSkuId)
      // console.log(res)
      context.commit('changeOneCount', { goodsId, goodsNum, goodsSkuId })
    },
    async deleteCart (context) {
      const arry = context.getters.getChecked
      const ids = arry.map(item => item.id)
      await deleteCart(ids)
      Toast('删除成功')
      context.dispatch('getCartList')
    }

  }
}
